package com.github.shiqiyue.app.config.webmvc;

import com.github.shiqiyue.app.common.utils.TimeZoneThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.TimeZone;

/***
 * time zone 过滤器
 * @author wenyao.wu
 * @since 2020/7/23
 */
@Slf4j
public class TimeZoneFilter extends OncePerRequestFilter {
    public static final String SESSION_KEY_TIME_ZONE = "M_TIME_ZONE_ID";

    public static final String HEADER_TIME_ZONE = "m-time-zone";

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    public static final String SAPI = "/sapi/**";

    public static final TimeZone CHINA_TIME_ZONE = TimeZone.getTimeZone("GMT+8");

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        try {
            String timeZoneId = (String) httpServletRequest.getSession().getAttribute(SESSION_KEY_TIME_ZONE);
            if (StringUtils.isNotBlank(timeZoneId)) {
                TimeZoneThreadLocal.setTimeZone(TimeZone.getTimeZone(timeZoneId));
            } else {
                String headerTimeZone = httpServletRequest.getHeader(HEADER_TIME_ZONE);
                if (StringUtils.isNotBlank(headerTimeZone)) {
                    TimeZoneThreadLocal.setTimeZone(TimeZone.getTimeZone("GMT" + headerTimeZone));
                } else {
                    TimeZoneThreadLocal.setTimeZone(TimeZone.getDefault());
                }
            }
        } catch (Exception e) {
            log.error("设置time zone失败", e);
        }
        try {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        } finally {
            TimeZoneThreadLocal.clear();
        }
    }
}
